<template>
    <div class="InboundList-box">
       <!-- 荣誉管理 -->
        <h3 class="mb16">荣誉管理</h3>
        <!-- 搜索栏 -->
        <serchForm :Form="inventoryForm" :FormLabel="inventoryFormLabel" @onSearch="onSearch" />
        <!-- 增删改查 -->
        <div class="function-box" v-if="checkPermi(['system:inventory:edit'])">
                <el-button class="addBtn2" @click="downloadS">下载荣誉证书</el-button>
        </div>
        <!-- 活动列表页面 -->
    <forTableCom
      :color="color"
      :idActive="idActive"
      :bg="bg"
      :total="total"
      :page="pageNum"
      :limit="pageSize"
      @handleSelectionChange="handleSelectionChange"
      @handleChange="handleChange"
      @updatePage="updatePage"
      @updateLimit="updateLimit"
      :tableHeaderData="inventoryTableHeaderData"
      :tableData="inventoryTableData"
      :honorShow='honorShow'
      @honorDownload="honorDownload"
      @honorView="honorView"
      @honorReject="honorReject"
      @honorPass="honorPass"
      :pagination="inventoryTableData.length>0"
    >
    </forTableCom>
    <!-- 添加或修改用户配置对话框 -->
      <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
         <el-form :model="form" :rules="rules" label-position="top" ref="userRef" label-width="80px">
            <div class="formItembox">
                  <el-form-item class="formItem" label="荣誉名称" prop="certificateName">
                     <el-input disabled  v-model="form.certificateName" placeholder="" />
                  </el-form-item>
                  <el-form-item class="formItem" label="荣誉级别" prop="certificateLevel">
                     <el-select disabled v-model="form.certificateLevel" placeholder="">
                        <el-option label="校级" value="1"></el-option>
                        <el-option label="市级" value="2"></el-option>
                        <el-option label="省级" value="3"></el-option>
                        <el-option label="国家级" value="4"></el-option>
                     </el-select>
                  </el-form-item>
                  <el-form-item class="formItem" label="获得时间" prop="issueDate">
                     <el-date-picker
                       disabled
                       class="input"
                         v-model="form.issueDate"
                         type="datetime"
                         placeholder=""
                       />
                  </el-form-item>
                  <el-form-item class="formItem" label="获奖集体/个人名称" prop="personalName">
                     <el-input disabled v-model="form.personalName" placeholder="" />
                  </el-form-item>
                  <el-form-item class="formItem" label="获奖学号" prop="userName">
                     <el-input disabled v-model="form.userName" placeholder="" />
                  </el-form-item>
                  <el-form-item class="formItem" label="组织" prop="deptNameList">
                     <!-- 组织 -->
                     <el-input disabled v-model="form.deptNameList" placeholder="" />
                  </el-form-item>
                  <el-form-item class="formItem" label="获奖年度" prop="timeYear">
                     <el-input disabled v-model="form.timeYear" placeholder="" />
                  </el-form-item>
                  <el-form-item class="formItem" label="获奖学期" prop="schoolYear">
                     <el-input disabled v-model="form.schoolYear" placeholder="" />
                  </el-form-item>        
                  <el-form-item class="formItem" label="获得分值" prop="creditValues">
                     <el-input disabled v-model="form.creditValues" placeholder="" />
                  </el-form-item>
                  <el-form-item v-show="submitType===-1 || submitType===2" class="formItem" label="加分/减分" prop="creditValue">
                     <el-input v-model="form.creditValue" placeholder="" />
                  </el-form-item>
                  <el-form-item style="visibility: hidden;" class="formItem" label="加分/减分" prop="title">
                      <p></p>
                  </el-form-item>
                  <el-form-item class="formItem" :label="submitType===-1||submitType===2? '更改原因' : '拒绝原因'">
                     <el-input  v-model="form.remark" type="textarea" :placeholder="submitType===-1||submitType===2?'请输入加分/减分原因' : '请输入拒绝原因'"></el-input>
                  </el-form-item>
                  <el-form-item class="formItem" label="企业评价/实习证明" prop="attachment">
                     <div class="file-list">
                      <div class="file-item">
                        <img class="file-img" :src="imgUrl" alt="" @click="openPhoto">
                      </div>
                     </div>
                  </el-form-item>
            </div>
         </el-form>
          
         <template #footer>
            <div class="dialog-footer">
               <el-button @click="cancel">取消</el-button> 
               <el-button v-show="submitType===-1" type="primary" @click="submitForm">通过</el-button>
               <el-button v-show="submitType===1" type="danger" @click="submitForm">拒绝</el-button>
               <el-button v-show="submitType===2" type="primary" @click="submitForm">提交</el-button>
            </div>
         </template>
      </el-dialog>

    <!-- 图片线上地址预览 -->
    <div v-if="showPreview" class="preview-modal" @click.self="closePreview">
      <div class="preview-content">
        <img :src="currentImage" class="preview-image" />
        <button class="close-button" @click="closePreview">
          <svg viewBox="0 0 24 24" width="24" height="24">
            <path fill="currentColor" d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
          </svg>
        </button>
      </div>
    </div>

    </div>
</template>

<script setup>
import { ref, reactive, toRefs,computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import serchForm from '@/components/inventory/serchForm.vue'
import { checkPermi } from '@/utils/permission.js'
import forTableCom from '@/components/forTableCom/index.vue'
import { ElMessage,ElMessageBox } from 'element-plus'
import {listUser} from '@/api/semester/semesterSet.js'
import {certificatesApi,certificatesPassAll,certificatesDetail,recordsPutApi} from '@/api/grade/honor.js'
import dayjs from 'dayjs';

const router = useRouter();
const route = useRoute();
const data = reactive({});
const { proxy } = getCurrentInstance();
let nodekey = ref(Math.random())

const title = ref("");
const open = ref(false);
const form = ref({
     certificateName: '', // 荣誉名称
     personalName:'',//获奖集体/个人名称
     issueDate:'',  //获得时间
     certificateLevel: '',//荣誉级别
     userName:'',    //获奖学号
     schoolYear:'',  //获奖学期
     certificateFile:'', //荣誉证书
     address:'', //活动地点
     remark:'',      //更改原因
     creditValues:'', //获得分值
     creditValue:'', //赋分
     deptNameList:'', //组织
     timeYear:'',    //获奖年度
  })
/** 重置操作表单 */
// function reset() {
//   form.value = {
     
//   };
//   proxy.resetForm("userRef");
// };
const rules = ref({
    creditValue: [{ required: true, message: "请输入分数", trigger: "blur" }],
  })

// 表单
let inventoryForm = ref({
  personalName:'',//获奖集体/个人名称
  issueDate: '', // 获奖时间
  certificateName: '', // 荣誉名称
  certificateLevel: '',//荣誉级别
  termId:'', //学期
  deptId:'', //组织
})
// 表单数据标题
let inventoryFormLabel = ref([
  {
    name: 'issueDate',
    label: '获奖时间',
    type: 'datetimerange',
  },
  {
    name: 'certificateName',
    label: '荣誉名称',
  },
  {
    name: 'certificateLevel',
    label: '荣誉级别',
    type:'select',
    client: [
      {
        label:'校级',
        value:1
      },
      {
        label:'市级',
        value:2
      },
      {
        label:'省级',
        value:3
      },
      {
        label:'国家级',
        value:4
      }
    ],
  },
  {
    name: 'personalName',
    label: '获奖集体/个人名称',
  },
  {
    name: 'deptId',
    label: '组织',
    type:'weixiao'
  },
  {
    name: 'termId',
    label: '学期',
    type:'select',
    client: [],
  },
])
// 查找
const onSearch = (v) => {
  console.log(v,'查看入库页面时间参数')
  // 每次查询后回到页1
  pageNum.value = 1
  v.startDate = v.issueDate[0]
  v.endDate = v.issueDate[1]
  certificatesApiFn(v)
}

// 显示操作栏
const honorShow = ref(true)
let idActive = 'id'
// 表格
let color = ref('#333')
let bg = ref('#d9d9d93b')
// 总条目数   pageSize 加 1
let total = ref(50)
// 当前页数
let pageNum = ref(1)
// 条数
let pageSize = ref(50)
// 存储勾选框的对象
let multipleSelection = ref([])
const piliangIds = ref('')
let ids = []
// 选中的列
const handleSelectionChange = (v) => {
  multipleSelection.value = v.map(item => item.id);        //过滤id
    ids = Array.from(multipleSelection.value)              //批量通过/拒绝用的
    piliangIds.value = multipleSelection.value.join(',')   //批量删除用的
}
// 分页器大小  当前分页器
const handleChange = (v) => {
  let { page, limit } = v.page
  pageNum.value = page
  pageSize.value = limit
  let params = inventoryForm.value
  certificatesApiFn(params)
}
// 当前页面位置发生变化
const updatePage = (v) => {
  console.log(v)
}
// 条目个数发生变化
const updateLimit = (v) => {
  console.log(v)
}
// 表格表头数据
let inventoryTableHeaderData = ref([
  {
    prop: 'certificateFile',
    label: '荣誉证书',
  },
  {
    prop: 'certificateName',
    label: '荣誉名称',
  },
  {
    prop: 'certificateLevel',
    label: '荣誉级别',
    certificateLevelHonorShow:true
  },
  {
    prop: 'personalName',
    label: '获奖集体/个人名称',
  },
  {
    prop: 'deptNameList',
    label: '组织',
    enterpriseDeptShow:true
  },
  {
    prop: 'issueDate',
    label: '获奖时间',
    sortable: true,
  },
  {
    prop: 'schoolYear',
    label: '学期',
  },
  {
    prop: 'status',
    label: '状态',
    statusDeatailActivityShow:true
  },
  {
    prop: 'creditValue',
    label: '获得积分',
  },
])
// 表格数据内容
let inventoryTableData = ref([])
const honorDownload = (val)=>{  //单个下载
      let {i , v} = val
      ElMessageBox.confirm(
    '确定要下载该证书吗?',
    '下载',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
        try {
        // 获取文件名（如果未提供则从URL中提取）
        var index = v.certificateFile.lastIndexOf('.')
        var name = v.certificateFile.slice(index)

        var index2 = v.certificateFile.lastIndexOf('/')
        var index3 = v.certificateFile.lastIndexOf('_')
        var name2 = v.certificateFile.slice(index2 + 1, index3)

        let filename = name2 + '' + name || '';  //获取文件名
        // if (!filename) {
        //     const urlParts = v.certificateFile.split('/');
        //     filename = urlParts[urlParts.length - 1].split('?')[0];
        // }

        // 使用fetch API获取文件
        const response = await fetch(v.certificateFile, {
            mode: 'cors', // 尝试跨域请求
            headers: new Headers({
                'Origin': window.location.origin,
            }),
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        // 获取文件blob
        const blob = await response.blob();
        
        // 创建对象URL
        const blobUrl = window.URL.createObjectURL(blob);
        
        // 创建隐藏的下载链接
        const link = document.createElement('a');
        link.href = blobUrl;
        link.download = filename;
        link.style.display = 'none';
        document.body.appendChild(link);
        
        // 触发点击
        link.click();
        
        // 清理
        setTimeout(() => {
            document.body.removeChild(link);
            window.URL.revokeObjectURL(blobUrl);
        }, 100);
    } catch (error) {
        console.error('下载失败:', error);
        
        // 如果fetch方式失败，尝试直接使用原始URL（适用于同源或服务器允许直接下载的情况）
        const link = document.createElement('a');
        link.href = v.certificateFile;
        link.download = filename || 'download';
        link.style.display = 'none';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })
}

const honorViewId = ref('')
const honorView = (val)=>{ //查看按钮
    let {i , v} = val
    submitType.value = 2
    open.value = true
    title.value = '荣誉详情'
    form.value.creditValue = ''
    form.value.remark = ''
    certificatesDetail(v.id).then(res=>{
        console.log(res,'打印详情数据');
        if(res.code===200){
             form.value.certificateName = res.data.certificateName
             form.value.certificateLevel = String(res.data.certificateLevel)
             form.value.issueDate = res.data.issueDate
             form.value.personalName = res.data.personalName
             form.value.deptId = res.data.deptId
             if(res.data.issueDate){
                 form.value.timeYear = res.data.issueDate.slice(0,4)
             }
             form.value.creditValues = res.data.creditValue
             form.value.userName = res.data.userName
             form.value.schoolYear = res.data.schoolYear
             urlShow.value = res.data.certificateFile
             backupId.value = res.data.id
             form.value.deptNameList = res.data.deptNameList.join(' / ')
             imgUrl.value = res.data.certificateFile
             honorViewId.value = res.data.studentCreditRecords.id
        }
    })
}
const honorReject = (val)=>{ //拒绝按钮
    let {i , v} = val
    submitType.value = 1
    open.value = true
    title.value = '荣誉详情'
    form.value.creditValue = ''
    form.value.remark = ''
    certificatesDetail(v.id).then(res=>{
        console.log(res,'打印详情数据');
        if(res.code===200){
             form.value.certificateName = res.data.certificateName
             form.value.certificateLevel = String(res.data.certificateLevel)
             form.value.issueDate = res.data.issueDate
             form.value.personalName = res.data.personalName
             form.value.deptId = res.data.deptId
             if(res.data.issueDate){
                 form.value.timeYear = res.data.issueDate.slice(0,4)
             }
             form.value.creditValues = res.data.creditValue
             form.value.userName = res.data.userName
             form.value.schoolYear = res.data.schoolYear
             urlShow.value = res.data.certificateFile
             backupId.value = res.data.id
             form.value.deptNameList = res.data.deptNameList.join(' / ')
             imgUrl.value = res.data.certificateFile
        }
    })
}

const submitType = ref(-1)
const backupId = ref(-1)
const backupUserId = ref(-1)
const honorPass = async(val)=>{ //通过按钮
    let {i , v} = val
    submitType.value = -1
    open.value = true
    title.value = '荣誉详情'
    form.value.creditValue = ''
    form.value.remark = ''
    certificatesDetail(v.id).then(res=>{
        console.log(res,'打印详情数据');
        if(res.code===200){
             form.value.certificateName = res.data.certificateName
             form.value.certificateLevel = String(res.data.certificateLevel)
             form.value.issueDate = res.data.issueDate
             form.value.personalName = res.data.personalName
             form.value.deptId = res.data.deptId
             if(res.data.issueDate){
                 form.value.timeYear = res.data.issueDate.slice(0,4)
             }
             form.value.creditValues = res.data.creditValue
             form.value.userName = res.data.userName
             form.value.schoolYear = res.data.schoolYear
             urlShow.value = res.data.certificateFile
             backupId.value = res.data.id
             form.value.deptNameList = res.data.deptNameList.join(' / ')
             imgUrl.value = res.data.certificateFile
        }
    })
}
let urlShow = ref('')
const editId = ref(-1)

/** 通过按钮提交 */
function submitForm() {
  proxy.$refs["userRef"].validate(valid => {
    if (valid) {
      if(submitType.value === -1){
            let obj = {
        id:backupId.value,
        status:1,
        creditValue:form.value.creditValue,
        remark:form.value.remark
    }
          certificatesPassAll(obj).then(res=>{
         if(res.code===200){
             ElMessage({
                 message: '通过成功',
                 type: 'success',
               })
               open.value = false
               certificatesApiFn()
         }
    })
  }else if(submitType.value === 1){
      let obj = {
        id:backupId.value,
        status:2,
        creditValue:form.value.creditValue,
        remark:form.value.remark
    }
          certificatesPassAll(obj).then(res=>{
         if(res.code===200){
             ElMessage({
                 message: '拒绝成功',
                 type: 'success',
               })
               open.value = false
               certificatesApiFn()
         }
    })
  }else if(submitType.value === 2){
       let obj = {
        id:honorViewId.value,
        status:1,
        creditValue:form.value.creditValue,
        remark:form.value.remark
    }
          recordsPutApi(obj).then(res=>{
         if(res.code===200){
             ElMessage({
                 message: '修改成功',
                 type: 'success',
               })
               open.value = false
               certificatesApiFn()
         }
    })
  }  
    }
  });
};
const downloadS = ()=>{ //批量下载荣誉证书
    if(ids.length==0){
       ElMessage({
                 message: '请先选择要下载的数据',
                 type: 'error',
               })
      return false
  }
  ElMessageBox.confirm(
    '确定要批量下载该证书吗?',
    '下载',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
         //下载证书方法
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })
}
const cancel = ()=>{  //取消
     open.value = false
}
// 查询荣誉列表数据
const certificatesApiFn = async (data = '') => {
  let page = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
  }
  let params = JSON.parse(JSON.stringify(Object.assign(page,data)))
  delete params.issueDate
  let res = await certificatesApi(params)
  let { code, rows } = res
  if (code == 200) {
    total.value = res.total
    inventoryTableData.value = rows
    console.log(rows,'打印荣誉列表数据');

    // 使用 map 转换 attachment，同时保留其他字段
    // inventoryTableData.value = rows.map(item => ({
    //   ...item, // 保留所有原有字段
    //   attachment: JSON.parse(item.attachment)[0] // 覆盖 attachment 为解析后的字符串
    // }));
  }
}



// 获取学期下拉信息
const listUserFn = async () => {
  let page = {
    pageNum: 1,
    pageSize: -1,
  }
  let {code, rows} = await listUser(page)
  if (code === 200) {
  rows.forEach((v) => {
    inventoryFormLabel.value[5].client.push({
      value: v.termId,
      label: v.schoolYear,
    })
  })
  }
}

// 图片上传
// 获取的图片
let urlList = ref([])
const handlerModelValue = (v) => {
       form.value.coverImageUrl = v


      //数组写法
      // urlList.value = v.map(item => item.url);  //过滤id
      // form.value.attachment = JSON.stringify(urlList.value)
      // console.log(form.value.attachment,'上传的图片地址');

  // var index = v.lastIndexOf("."); //用于返回指定字符串在当前字符串中最后一次出现的位置。
  // var name = v.slice(index); //目的用来截取.jpg等字段
  // form.value.fileType = name.replace(".", "");
  
}
const size = (val)=>{
     console.log(val,'文件大小');
    //  form.value.fileSize = val
}

//预览功能
let imgUrl = ref('')
const showPreview = ref(false);
const currentImage = ref('');

//打开预览
const openPhoto = ()=>{
         currentImage.value = imgUrl.value;
         showPreview.value = true;
         document.body.style.overflow = 'hidden'; // 防止背景滚动
}
// 关闭预览
const closePreview = () => {
  showPreview.value = false;
  document.body.style.overflow = '';
};
// 点击ESC键关闭预览
const handleKeyDown = (e) => {
  if (e.key === 'Escape' && showPreview.value) {
    closePreview();
  }
};
// 添加键盘事件监听
window.addEventListener('keydown', handleKeyDown);

onMounted(()=>{
    Promise.all([certificatesApiFn(),listUserFn()])
})

</script>

<style lang='scss' scoped>
.InboundList-box {
    padding: 16px;
    .function-box {
    display: flex;
    align-items: center;
  }
}
.dialog-footer {
  display: flex;
  justify-content: center; /* 水平居中 */
}
.formItembox {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      // justify-content: center;
      box-sizing: border-box;

      .formItem {
        width: 30%;
        // margin-right: 30px;
      }
      .formItem:nth-child(12) {
        width: 100%;
        margin-right:0;
      }
      .formItem:nth-child(3) {
        margin-right:0;
      }
      .formItem:last-child{
        margin-right:0;
        width: 100%;
        .file-list{
           width: 100%;
           border: 1px solid #ccc;
           display: flex;
           justify-content: center;
           padding: 10px 0;
           .file-item{
            width: 200px;
            height: 200px;
              .file-img{
                 width: 100%;
                 height: 100%;
              }
           }
        }
      }
    }
:deep(.el-select .el-input__wrapper) {  //下拉框
  width: 240px;
}
:deep(.el-date-editor){  //日期选择器
   width: 240px;
}
.formItem :deep(.el-input) {  //input输入框
  width: 240px;
}
:deep(.el-textarea__inner){   //文本域
    height: 80px;
}


.excel-table{
   border: 1px solid rgb(0, 0, 0);
        border-image: none;
        width: 100%;
        text-align: center;
        border-collapse: collapse;
        background-color: rgb(255, 255, 255);
}
:deep(.el-form-item:nth-child(4) .el-form-item__label) {
  margin-left: 0;
}

//图片预览样式
.preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.preview-content {
  position: relative;
  max-width: 90%;
  max-height: 90%;
}

.preview-image {
  max-width: 100%;
  max-height: 90vh;
  object-fit: contain;
  border-radius: 4px;
}

.close-button {
  position: absolute;
  top: -40px;
  right: -40px;
  background: none;
  border: none;
  color: white;
  cursor: pointer;
  font-size: 24px;
  padding: 10px;
  transition: transform 0.2s;
}

.close-button:hover {
  transform: scale(1.2);
}

@media (max-width: 768px) {
  .close-button {
    top: -50px;
    right: 10px;
  }
}

</style>

